var ShiftingCommon = function(){
	var $ = jQuery, $page, $form, $date, $timeInput, $start, $end, $period, $wCenter, 
	dFormat = 'yyyy-MM-dd', dtFormat= 'yyyy-MM-dd HH:mm', perDay = 24 * 60 * 60 * 1000,
	getNextDate = function(date) {
		if (date.getTime) {
			return new Date(date.getTime() + perDay);
		} else {
			return new Date(date.parseDate(dFormat).getTime() + perDay);
		}
	},
	today = new Date().formatDate(dFormat),
	initPage = function($p, isEdit) {
		$page = $p;
		$form = $('form:first', $page);
		$timeInput = $('[name=startDateTime],[name=endDateTime]', $form);
		$date = $('[name=theDate]', $form);
		if (!isEdit) {
			$date.val(today);
		}
		$start = $('[name=startDateTime]', $form); 
		$end = $('[name=endDateTime]', $form);
		$period = $('#periodSelect', $form).on('change', function(){
			var selectedIndex = this.selectedIndex, $option = $('>option', $(this)).eq(selectedIndex);
			$start.val($option.attr('minDate')).change();
			$end.val($option.attr('maxDate')).change();
		});
		$wCenter = $('[name=shiftingWorkcenterCode]', $form).on('change', function(){
			loadPeriods(isEdit);
			isEdit = false;
		});
		$date.on('change', function(){
			var date = this.value;
			if (date) {
				$timeInput.attr('minDate', date);
				$timeInput.attr('maxDate', getNextDate(date).formatDate(dFormat));
			} else {
				$timeInput.attr('minDate', today);
				$timeInput.attr('maxDate', getNextDate(today).formatDate(dFormat));
			}
			loadPeriods(isEdit);
			isEdit = false;
		}).change();
	},
	loadPeriods = function(isEdit) {
		var wCenterCode = $wCenter.val(),
		theDate = $date.val();
		
		$period.empty();
		if (!isEdit) {
			$start.val('');
			$end.val('');
		}
		
		if(wCenterCode && theDate){
			$.ajax({
				url: hostUrl + '/shifting/getWorkDayPeriods',
				type: 'POST',
				global: false,
				data: {
					workcenterCode: wCenterCode,
					date: theDate
				},
				dataType: 'json',
				success: function(periods) {
					if (periods && periods.length) {
						$.each(periods, function(){
							var period = this, isNextDay = period.nextDayFlag == 1, isSpanDay = period.spanDaysFlag == 1,
							
							$option = $('<option/>').attr({
								minDate: isNextDay ? getNextDate(theDate).formatDate(dFormat) + ' ' + period.startTime : theDate + ' ' + period.startTime,
								maxDate: isNextDay || isSpanDay ? getNextDate(theDate).formatDate(dFormat) + ' ' + period.endTime : theDate + ' ' + period.endTime
							}).text((isNextDay ? '次日' : '当日') + period.startTime + ' - ' + (isNextDay || isSpanDay ? '次日' : '当日') + period.endTime);
							
							$period.append($option);
						});
						$period[0].selectedIndex = -1;
					}
				},
				error: DWZ.ajaxError
			});
		}
	},
	validate = function(shiftingObj) {
		var isOverlapping = true;
		$.ajax({
			url: hostUrl + '/shifting/validateShifting',
			type: 'POST',
			async: false,
			data: shiftingObj,
			dataType: 'json',
			success: function(json) {
				var dialogGridOps = {
					height: 160,
					autoLoad: false,
					hasBorder: true,
					orderable: false,
					pageable: false,
					columns: [
						{field: '_index', text: '序号', width: 20},
						{field: 'personnelCode', text: '人员编号', width: 100, orderTable: 's'},
						{field: 'theDate', type: 'date', format: dFormat, text: '日期', width: 80},
						{field: 'startDateTime', type: 'date', format: dtFormat, text: '开始时间', width: 120},
						{field: 'endDateTime', type: 'date', format: dtFormat, text: '结束时间', width: 120}
					]
				};
				if (json.overlappingShiftings && json.overlappingShiftings.length) {
					dialogGridOps.fillData = json.overlappingShiftings;
					$.pdialog.open('', 'arrangedShiftings', '时间范围冲突', {height: 300, width: 570, max: false, mask: true, resizable: false, maxable: false, minable: false, callback: function($content, $dialog){
						$('#errorMsg', $page).clone().show().text('添加失败,时间起止范围冲突').appendTo($content);
						var $shiftingsGrid = $('<div/>').appendTo($content);
						$shiftingsGrid.jGrid(dialogGridOps);
						$('#closeBtn', $page).clone().show().appendTo($content);
						$("button.close", $content).click(function(){
							$.pdialog.close($dialog);
							return false;
						});
					}});
				} else {
					var firstStartTime = shiftingObj.startDateTime, lastEndTime = shiftingObj.endDateTime;
					if (json.firstStartTime) {
						var startTime = new Date(json.firstStartTime);
						if (startTime.getTime() < firstStartTime.getTime()) {
							firstStartTime = startTime;
						}
					}
					if (json.lastEndTime) {
						var endTime = new Date(json.lastEndTime);
						if (endTime.getTime() > lastEndTime.getTime()) {
							lastEndTime = endTime;
						}
					}
					// 如果第一个开始时间和最后一个结束时间相差超过24小时则不能保存
					if (lastEndTime.getTime() - firstStartTime.getTime() > perDay) {
						if (json.shiftings && json.shiftings.length) {
							dialogGridOps.fillData = json.shiftings;
							$.pdialog.open('', 'arrangedShiftings', '工作时段详情', {height: 300, width: 570, max: false, mask: true, resizable: false, maxable: false, minable: false, callback: function($content, $dialog){
								$('#errorMsg', $page).clone().show().text('添加失败,时间起止范围超过24小时').appendTo($content);
								var $shiftingsGrid = $('<div/>').appendTo($content);
								$shiftingsGrid.jGrid(dialogGridOps);
								$('#closeBtn', $page).clone().show().appendTo($content);
								$("button.close", $content).click(function(){
									$.pdialog.close($dialog);
									return false;
								});
							}});
						} else {
							alertMsg.error('当前日期工作时段起止时间不能超过24小时！');
						}
					} else {
						isOverlapping = false;
					}
				}
			},
			error: DWZ.ajaxError
		});
		return isOverlapping;
	},
	batchValidate = function(shiftings, date) {
		var isInvalid = true;
		DWZ.ajax({
			url: hostUrl + '/shifting/validateShiftingList',
			async: false,
			data: {
				theDate: date,
				shiftings: JSON.stringify(shiftings)
			},
			alert: false,
			success: function(json) {
				isInvalid = json.data;
			}
		});
		return isInvalid;
	};
	return {
		initPage: initPage,
		validate: validate,
		batchValidate: batchValidate
	};
};